package ro.savatech.pg.flightlog;

import java.util.Calendar;

/**
 * An entry in the flight index found in the devicemem.
 * 
 * @author Dan Corneanu
 * 
 */
public class FlightIndexEntry {
	public static final short RECORD_SIZE = 0x0015; // 21 bytes

	private static final short START_DATE = 0x000B; // 11 bytes
	private static final short START_TIME_MM = 0x000E;
	private static final short START_TIME_HH = 0x000F;
	private static final short ADDR_START = 0x0011;
	private static final short ADDR_END = 0x0013;

	private byte day;

	private byte month;

	private byte year;

	private byte mm;

	private byte hh;

	private short addrStart;

	private short addrEnd;

	private FlightIndexEntry() {

	}

	public static FlightIndexEntry fromRaw(byte[] raw) {
		if (RECORD_SIZE != raw.length) {
			throw new IllegalArgumentException(String.format(
					"The size of a flight record must be exactlly 0x%X.",
					RECORD_SIZE));
		}

		FlightIndexEntry entry = new FlightIndexEntry();
		short day = (short) (raw[START_DATE] & 0xFF);
		short month = (short) (raw[START_DATE + 1] & 0xFF);
		short year = (short) (raw[START_DATE + 2] & 0xFF);

		entry.day = Byte.parseByte(Integer.toHexString(day));
		entry.month = Byte.parseByte(Integer.toHexString(month));
		entry.year = Byte.parseByte(Integer.toHexString(year));

		short mm = (short) (raw[START_TIME_MM] & 0xFF);
		short hh = (short) (raw[START_TIME_HH] & 0xFF);

		entry.mm = Byte.parseByte(Integer.toHexString(mm));
		entry.hh = Byte.parseByte(Integer.toHexString(hh));

		short addrStart = (short) ((raw[ADDR_START] & 0xFF) + ((raw[ADDR_START + 1] - 0x05) << 8));
		short addrEnd = (short) ((raw[ADDR_END] & 0xFF) + ((raw[ADDR_END + 1] - 0x05) << 8));

		entry.addrStart = addrStart;
		entry.addrEnd = addrEnd;

		return entry;
	}

	@Override
	public String toString() {
		StringBuffer buff = new StringBuffer();
		buff.append(String.format("Flight date: %02d:%02d:20%02d %02d:%02d\n",
				this.day, this.month, this.year, this.hh, this.mm));
		buff.append(String.format("Address start/end: 0x%04X / 0x%04X\n",
				this.addrStart, this.addrEnd));
		return buff.toString();
	}

	public short getAddrStart() {
		return addrStart;
	}

	public short getAddrEnd() {
		return addrEnd;
	}

	public int getDelta() {
		// TODO read this from flight index
		return 15; // seconds
	}

	public Calendar getStartTime() {
		Calendar start = Calendar.getInstance();
		start.set(Calendar.HOUR_OF_DAY, this.hh);
		start.set(Calendar.MINUTE, this.mm);

		return start;
	}
}
